<template>
	<el-dialog title="下级授权" v-model="visible" :close-on-click-modal="false" draggable width="600px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="16" class="mb20">
					<el-form-item label="授权单位" prop="deptId">
						<el-tree-select
							v-model="form.deptId"
							:data="parentData"
							:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
							clearable
							filterable
							check-strictly
							:render-after-expand="false"
							placeholder="请选择授权单位"
							@change="handleTreeChange"
							ref="treeRef"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="16" class="mb20">
					<el-form-item label="验证码" prop="code">
						<el-input v-model="form.code" placeholder="请输入验证码" maxlength="4" />
					</el-form-item>
				</el-col>
				<el-col :span="8" class="mb20">
					<div class="flex items-center">
						<div class="h-[32px]">
							<img :src="codeImg" v-show="!!codeImg" class="w-full h-full" />
						</div>
						<el-icon @click="getCodeImg" size="22" color="#409EFF" class="ml-2 cursor-pointer"><RefreshLeft /></el-icon>
					</div>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">下一步</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="subordinateAuthDialog">
import { useMessage, useMessageBox } from '/@/hooks/message';
import { getCaptcha } from '/@/api/platform/basicDeviceStock';
import { addObj, checkCode } from '/@/api/platform/basicAuthorizationRecord';
import { deptTree } from '/@/api/admin/dept';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const codeImg = ref();
const selectObjs = ref<any[]>([]);
const parentData = ref([]);
const treeRef = ref();
const currentNode = ref();
// 定义字典

// 提交表单数据
const form = reactive({
	code: '',
	deptId: null,
});

// 定义校验规则
const dataRules = ref({
	deptId: [{ required: true, message: '请选择授权单位', trigger: 'blur' }],
	code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
});
// 获取验证码
const getCodeImg = () => {
	getCaptcha().then((res: any) => {
		codeImg.value = res.data.codeImg;
	});
};
// 打开弹窗
const openDialog = (objs: any[]) => {
	visible.value = true;
	selectObjs.value = objs;
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	getCodeImg();
	getDeptData();
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		await authPhone();
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
// 校验授权单位
const authPhone = async () => {
	try {
		await checkCode(form);
	} catch (err: any) {
		useMessage().error(err.msg);
		return;
	}
	try {
		await useMessageBox().confirm(`确定将型号授权给${currentNode.value.name}吗？`);
	} catch (err: any) {
		return;
	}
	try {
		const params = Object.assign(form, { deviceModelList: selectObjs.value });
		await addObj(params);
		visible.value = false;
		useMessage().success('授权成功');
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
		return;
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
const handleTreeChange = () => {
	const node = unref(treeRef).getCurrentNode();
	currentNode.value = node;
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
